package com.conyou.matryoshka.plugin;

import android.content.Context;
import android.util.Log;

import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Method;
import java.util.Objects;

import com.google.gson.Gson;

public class NativeInvoker extends CordovaPlugin {

  private static final Gson gson = new Gson();

  @Override
  public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {

    cordova.getThreadPool().execute(() -> {
      try {
        JSONObject payload = new JSONObject(args.getString(0));

        String clazz = payload.getString("classFullName");
        Class<?> targetClass = Class.forName(clazz);
        Class<?>[] parameterTypes = { JSONObject.class, Context.class };

        Method method = targetClass.getDeclaredMethod(action, parameterTypes);
        Object targetInstance = targetClass.newInstance();

        Object[] arguments = { payload.optJSONObject("params"), cordova.getContext() };

        Object result = method.invoke(targetInstance, arguments);
        callbackContext.success(gson.toJson(result));

      } catch (Exception e) {
        Log.e("PLUGIN_ERR", Objects.requireNonNull(e.getMessage()));
        callbackContext.error("ERROR");
      }
    });

    return true;

  }

}